﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace memcached.Tx
{
    /// <summary>
    /// If value is null or not a number, it is removed on Rollback.
    /// </summary>
    internal sealed class IncrementOp : KeyedOp
    {
        [System.Diagnostics.DebuggerHidden]
        public IncrementOp(ICacheAdvanced real, ICacheAdvanced temp, string key, long startAt)
            : base(real, temp, key)
        {
            StartAt = startAt;
        }

        private readonly long StartAt;
        private long? Original;
        private bool Done;

        public override string Name
        {
            [System.Diagnostics.DebuggerHidden]
            get { return "Increment:" + Key; }
        }

        public override object Execute()
        {
            return ((ICacheAdvanced)Temp).Increment(Key, StartAt);
        }

        public override bool Persist()
        {
            bool res;
            object org = Store.Get(Key, out res);
            if (res)
            {
                if (org is long)
                    Original = (long)org;
                else
                    if (org is string)
                        Original = Convert.ToInt64((string)org);
                long newVal = ((ICacheAdvanced)Store).Increment(Key, StartAt);
                if (Original.HasValue)
                    res = newVal > Original.Value;
                else
                    res = newVal >= StartAt;
            }
            Done = res;
            return Done;
        }

        public override bool Rollback()
        {
            if (Done)
                if (Original.HasValue)
                    return Store.Set(Key, Original.Value.ToString());// reset to original
                else
                    // the Key was not present before Increment
                    return Store.Remove(Key);
            return true;// if it was not set, that nothing to reset
        }
    }
}
